import net.sourceforge.tess4j.ITessAPI;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.Word;
import net.sourceforge.tess4j.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ColorConvertOp;
import java.awt.image.Kernel;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class OCRImageProcessing {

    private static final Logger log = LoggerFactory.getLogger(OCRImageProcessing.class);

    public static void main(String[] args) throws Exception {
        File imageFile = new File("src\\main\\resources\\tess4j\\split\\22.png");
        System.out.println(imageFile.exists());

        ITesseract instance = new Tesseract();
        instance.setDatapath("src\\main\\resources\\tess4j\\");
        instance.setLanguage("chi_sim+eng");
//        instance.setTessVariable("tessedit_char_whitelist", "+-1234567890");

        System.out.println(instance.doOCR(imageFile));

        //按照每个字取词
        int pageIteratorLevel = ITessAPI.TessPageIteratorLevel.RIL_SYMBOL;
        log.info("PageIteratorLevel: " + Utils.getConstantName(pageIteratorLevel, ITessAPI.TessPageIteratorLevel.class));
        BufferedImage bi = ImageIO.read(imageFile);
        outChange(bi);

        List<Word> result = instance.getWords(bi, pageIteratorLevel);

        // 在识别的同级目录下创建输出文件，文件名格式为：源文件名称_年月日时分秒
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String outputFileName = imageFile.getName().substring(0, imageFile.getName().lastIndexOf('.')) + "_" + sdf.format(new Date()) + ".png";
        File outputFile = new File(imageFile.getParent(), outputFileName);

        // 复制原始图像用于绘制框框
        BufferedImage outputImage = deepCopyBufferedImage(bi);

        // 绘制识别区域的框框并保存输出图像
        Graphics2D g2d = outputImage.createGraphics();
        g2d.setColor(Color.RED);
        g2d.setStroke(new BasicStroke(2));

        for (Word word : result) {
            Rectangle boundingBox = word.getBoundingBox();
            g2d.drawRect(boundingBox.x, boundingBox.y, boundingBox.width, boundingBox.height);
        }

        g2d.dispose();

        ImageIO.write(outputImage, "png", outputFile);

        //print the complete result
        for (Word word : result) {
            log.info(word.toString());
        }
    }

    private static void outChange(BufferedImage bi) throws IOException {
        for (int i = 1; i < 14; i++) {
            // 2. 使用ColorConvertOp将原始图像转换为指定的图像类型（这里转换为灰度图像 TYPE_BYTE_GRAY）
            BufferedImage mergedImage = new BufferedImage(bi.getWidth(), bi.getHeight(), i);
            mergedImage.setRGB(bi.getWidth(), bi.getHeight(), bi.getRGB(bi.getWidth(), bi.getHeight()));
            File outputFile = new File("output_image_path" + i + ".jpg"); // 替换为实际的输出文件路径
            ImageIO.write(mergedImage, "jpg", outputFile);

            System.out.println("图像类型转换并保存成功！");
        }
    }

    private static BufferedImage deepCopyBufferedImage(BufferedImage bi) {
        BufferedImage copy = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());
        Graphics2D g2 = copy.createGraphics();
        g2.drawImage(bi, 0, 0, null);
        g2.dispose();
        return copy;
    }
}